package com.edwin.websitebe.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edwin.websitebe.model.BoxGame;
import com.edwin.websitebe.model.Game;
import com.edwin.websitebe.model.Member;
import com.edwin.websitebe.model.MemberGame;
import com.edwin.websitebe.service.BoxGameService;
import com.edwin.websitebe.service.GameService;
import com.edwin.websitebe.service.MemberGameService;
import com.edwin.websitebe.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/memberGame")
@Slf4j
public class MemberGameController {

    @Autowired
    private MemberGameService memberGameService;

    @Autowired
    private BoxGameService gameService;

    @GetMapping("/listByMemberId")
    public ResultVO listByMemberId(@RequestParam Long memberId) {
        LambdaQueryWrapper<MemberGame> wrapper = new QueryWrapper<MemberGame>().lambda()
                .eq(Objects.nonNull(memberId), MemberGame::getMemberId, memberId)
                .orderByDesc(MemberGame::getCreateTime);
        List<MemberGame> list = memberGameService.list(wrapper);
        for (MemberGame memberGame : list) {
            BoxGame game = gameService.getById(memberGame.getGameId());
            memberGame.setGameName(game.getGameName());
        }
        return new ResultVO().success(list);
    }
    
    @PostMapping("/setMemberGame")
    public ResultVO setMemberGameByMemberId(@RequestBody List<MemberGame> list) {

        if (CollectionUtil.isEmpty(list)) {
            return new ResultVO().success();
        }
        Long memberId = list.get(0).getMemberId();

        // 删除
        LambdaQueryWrapper<MemberGame> deleteWrapper = new QueryWrapper<MemberGame>().lambda()
                .eq(MemberGame::getMemberId, memberId);
        memberGameService.remove(deleteWrapper);

        // 保存
        memberGameService.saveBatch(list);

        return new ResultVO().success();
    }


}
